import React, { useEffect, useState, Fragment } from 'react'
import { Button, message, Table, Tabs, Popconfirm } from 'antd'
import moment from 'moment'
import { getProductList, setProductStatus } from '../../../request/product'
import './style.scss'

function ProductList(props) {
  const [currentPage, setCurrentPage] = useState(1)
  const [totalCount, setTotalCount] = useState(0)
  const [isLoading, setIsLoading] = useState(false)
  const [packageList, setPackageList] = useState([])
  const [valid, setValid] = useState(1)
  const pageSize = 30

  useEffect(() => {
    getList().catch(e => console.log(e.message))
  }, [valid])

  const setStatus = async(data) => {
    const { code, message: errMsg } = await setProductStatus(data)
    if (code) {
      message.error(errMsg)
      return false
    }
    message.success('操作成功')
    getList().catch(e => console.log(e.message))
  }

  const getList = async(page = 1) => {
    setIsLoading(true)
    const { code, message: errMsg, data } = await getProductList({
      valid,
      page,
      size: pageSize
    })
    setIsLoading(false)
    if (code) {
      message.error(errMsg)
      return false
    }
    setPackageList(data.list)
    setTotalCount(data.total_result)
    setCurrentPage(data.page)
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      align: 'center',
      width: '100px',
      render: (text, record, index) => (index + 1)
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      render: (text, record) => (<Button type="link" onClick={() => window.open(`//www.lfcxwifi.com/?code=${record.code}`)}>{text}</Button>)
    },
    {
      title: '页面名称',
      dataIndex: 'page_name'
    },
    {
      title: '商品编码',
      dataIndex: 'code'
    },
    {
      title: '商品渠道',
      dataIndex: 'partner_name'
    },
    {
      title: '代理商',
      dataIndex: 'user_name',
      render: text => (<span>{text || '-'}</span>)
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      render: text => (<span>{moment(text * 1000).format('YYYY-MM-DD HH:mm:ss')}</span>)
    },
    {
      title: '操作',
      width: 200,
      align: 'center',
      render: (text, record) => (
        <Fragment>
          <Button
            size="small"
            style={{ marginRight: '10px' }}
            onClick={() => props.history.push(`/product/edit/${record.id}`)}
          >
            编辑
          </Button>
          {!!valid && (
            <Popconfirm
              title="确定下架该产品吗"
              okText="确定"
              cancelText="取消"
              onConfirm={() => setStatus({ id: record.id, valid: 0 })}
            >
              <Button size="small" type="danger">下架</Button>
            </Popconfirm>
          )}
          {!valid && (
            <Popconfirm
              title="确定上架该产品吗"
              okText="确定"
              cancelText="取消"
              onConfirm={() => setStatus({ id: record.id, valid: 1 })}
            >
              <Button size="small" type="primary">上架</Button>
            </Popconfirm>
          )}
        </Fragment>
      )
    }
  ]

  return (
    <div className="product-list">
      <div className="menu">
        <Button
          type="primary"
          onClick={() => {
            props.history.push('/product/add')
          }}
        >
          新增商品
        </Button>
      </div>
      <Tabs onChange={key => setValid(Number(key))}>
        <Tabs.TabPane tab="在售中商品" key={1}></Tabs.TabPane>
        <Tabs.TabPane tab="已下架商品" key={0}></Tabs.TabPane>
      </Tabs>
      <div className="content">
        <Table
          loading={isLoading}
          rowKey={row => row.id}
          columns={columns}
          dataSource={packageList}
          onChange={page => getList(page.current)}
          pagination={{
            defaultCurrent: currentPage,
            current: currentPage,
            total: totalCount,
            pageSize,
            showTotal: total => `共 ${total} 条`
          }}
        />
      </div>
    </div>
  )
}

export default ProductList
